package com.joycessh.exception;

import com.joycessh.domain.ResultCode;
import com.joycessh.domain.ResultJson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Author Joycessh
 * @Description 异常处理类: 使用@@ControllerAdvice和@ExceptionHandler实现全局Controller层的异常处理
 * @Date 4/18/19 3:33 PM
 */
@RestControllerAdvice    //控制器增强，使用AOP对Controller控制器进行增强
@Slf4j
public class DefaultExceptionHandler {
    /**
     * 处理所有自定义异常
     * @author Joycessh
     * @param e
     * @return com.joycessh.domain.ResultJson
     * @date 4/18/19 3:35 PM
     */
    @ExceptionHandler(CustomException.class)
    public ResultJson handleCustomException(CustomException e){
        log.error(e.getResultJson().getMsg().toString());
        return e.getResultJson();
    }

    /**
     * 处理参数校验异常
     * @author Joycessh
     * @param e
     * @return com.joycessh.domain.ResultJson
     * @date 4/18/19 3:35 PM
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultJson handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error(e.getBindingResult().getFieldError().getField() + e.getBindingResult().getFieldError().getDefaultMessage());
        return ResultJson.failure(ResultCode.BAD_REQUEST, e.getBindingResult().getFieldError().getDefaultMessage());
    }
}
